package org.smart4j.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClassUtil {

    private static final Logger logger = LoggerFactory.getLogger(ClassUtil.class);

    /**
     * jar中的文件路径分隔符
     */
    private static final char SLASH_CHAR = '/';

    /**
     * 包名分隔符
     */
    private static final char DOT_CHAR = '.';

    /**
     * 获取类加载器
     * @return 线程上下文ClassLoader
     */
    public static ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

    public static Class<?> loadClass(String className){
        return loadClass(className,true);
    }

    /**
     * 加载类
     * @param className 要加载的类名称
     * @param isInitialized 在加载类时是否初始化
     * @return 指定类名的Class
     */
    public static Class<?> loadClass(String className,boolean isInitialized){
        Class<?> cls;
        try {
            cls = Class.forName(className,isInitialized,getClassLoader());
        } catch (ClassNotFoundException e) {
            logger.error("load class failure",e);
            throw new RuntimeException(e);
        }
        return cls;
    }

    /**
     * 加载指定包下所有类及子类
     * @param packageName 基础包名称
     * @return 包下所有类及子类列表
     */
    public static Set<Class<?>> getClassSet(String packageName){
        return getClassSet(packageName,true);
    }

    /**
     * 加载指定包下所有类
     * @param packageName 基础包名
     * @param recursive 是否递归搜索
     * @return 该包名下的所有类
     */
    public static Set<Class<?>> getClassSet(String packageName,boolean recursive){
        Set<Class<?>> classSet = new HashSet<Class<?>>();
        try {
            //1.- 从包得到实际的物理资源URL
            Enumeration<URL> iterator = getClassLoader().getResources(packageName.replace(DOT_CHAR, File.separatorChar));
            while (iterator.hasMoreElements()){
                //2.- 读取一个资源
                URL url = iterator.nextElement();
                if(url!=null) {
                    //3.- 读取资源协议
                    String protocol = url.getProtocol();
                    //4. - 1如果是一个file，处理方式
                    if(protocol.equals("file")){
                        String packagePath = url.getPath().replaceAll("%20","");
                        addClass(classSet,packagePath,packageName);
                        //4. - 2如果是一个jar，处理方式
                    }else if(protocol.equals("jar")){
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if(jarURLConnection!=null){
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if(jarFile!=null){
                                Enumeration<JarEntry> jarEntries = jarFile.entries();
                                while (jarEntries.hasMoreElements()){
                                    JarEntry jarEntry = jarEntries.nextElement();
                                    String jarEntryName = jarEntry.getName();
                                    if(jarEntryName.endsWith(".class")){
                                        String className = jarEntryName.substring(0,jarEntryName.lastIndexOf(".")).replaceAll("/",".");
                                        doAddClass(classSet,className);
                                    }
                                }
                            }
                        }
                    }
                }

            }

        } catch (IOException e) {
            logger.error("load package class set failure",e);
            throw new RuntimeException(e);
        }
        return classSet;
    }

    private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class")  || file.isDirectory());
            }
        });
        for(File file:files){
            String fileName = file.getName();
            if(file.isFile()){
                String className = fileName.substring(0,fileName.lastIndexOf("."));
                if(StringUtil.isNotEmpty(packageName)){
                    className = packageName+"."+className;
                }
                doAddClass(classSet,className);
            }else{
                String subPackagePath = fileName;
                if(StringUtil.isNotEmpty(packagePath)){
                    subPackagePath = packagePath + File.separator + subPackagePath;
                }
                String subPackageName = fileName;
                if(StringUtil.isNotEmpty(packageName)){
                    subPackageName = packageName +"."+subPackageName;
                }
                addClass(classSet,subPackagePath,subPackageName);
            }
        }
    }

    private static void doAddClass(Set<Class<?>> classSet,String className){
        Class<?> cls = loadClass(className,false);
        classSet.add(cls);
    }

    public static void main(String[] args){
        ClassUtil.getClassSet("org.smart4j.framework");
    }


}
